<?php
/**
 * @name OrderController
 * @author xuebingwang
 * @desc 商城订单控制器
 * @see http://www.php.net/manual/en/class.yaf-controller-abstract.php
*/
class InfoController extends MemberController {
    
    function indexAction(){

        $curl = new Curl();
        $resp = $curl->setData(['unionid'=>$this->user['unionid']])
                    ->send('mall/order/getTotal');

        $total = ['order'=>0,'friend'=>0];

        if(!empty($resp) && $resp['errcode'] == 0){
            $total['order'] = $resp['all'];
        }
        $resp = $curl->setData2(['query'=>['mobileNum'=>$this->user['unionid']]])
            ->setApiUrl($this->config->url->api->sdp)
            ->send('distribution/getInfo');

        if(!empty($resp) && $resp['errcode'] == 0){
            $total['friend'] = $resp['firstLevelNumber'];
        }


        $info = M('t_wx_user')->get(
            [
                'userid',
                'unionid',
                'qr_ticket',
                'qr_expire_seconds',
                'qr_create_time',
            ],
            ['userid'=>$this->user['userid']]
        );
        $qrcode = get_wx_qrcode($this->wechat,$info);
        $this->getView()->assign('qrcode',$qrcode);

        $this->getView()->assign('total',$total);

        $this->getView()->assign('user',$this->user);
    }

    public function setMobileAction(){

        if(IS_POST){

            if(!empty($this->user['mobile'])){
                $this->error('您已经绑定手机号码了！');
            }

            $mobileNum = trim($this->getRequest()->getPost('mobileNum',''));
            if(empty($mobileNum)){
                $this->error('手机号码不能为空');
            }

            $smsCode = trim($this->getRequest()->getPost('smsCode',''));
            if(empty($smsCode)){
                $this->error('验证码不能为空');
            }

            $my_code = session('bindSmsCode');

            if(empty($my_code) || !is_array($my_code)){
                $this->error('您还未获取短信验证码！');
            }
            if($mobileNum != $my_code['mobile'] || $smsCode != $my_code['code']){
                $this->error('验证码不匹配！');
            }
            if(time()-$my_code['time'] > 600){
                $this->error('验证码已过期！');
            }
            $model = new UcenterMemberModel();

            $data = [
                        'username'=>$mobileNum,
                        'mobile'=>$mobileNum,
                        'reg_time'=>time(),
                        'wx_userid'=>$this->user['userid'],
                        'reg_ip'=>get_client_ip(1),
                        'status'=>1
                    ];
            $ff = $model->insert($data);
            
            if($ff){
                $this->user['mobile'] = $mobileNum;
                session('user_auth',$this->user);
                session('bindSmsCode',null);
                $this->success('手机号码绑定成功！');
            }

            $this->error('手机号码绑定失败，请重新再试！');
        }
    }

    function getChildCountAction(){


        $levelLike = M('t_wsyq_distribution_user_relation')->get('levelNo',['userId'=>$this->user['unionid']]);

        if(empty($levelLike)){
            $this->error('没有下线!');
        }

        $total[] = M()->query(str_replace('*','count(*)',$this->_child_sql($levelLike,0)))->fetchColumn();
        $total[] = M()->query(str_replace('*','count(*)',$this->_child_sql($levelLike,1)))->fetchColumn();
        $total[] = M()->query(str_replace('*','count(*)',$this->_child_sql($levelLike,2)))->fetchColumn();

        $this->ajaxReturn(['msg'=>'','status'=>1,'total'=>$total]);
    }

    private function _child_sql($levelNo,$type){

        $levelLen = strlen($levelNo)+12;

        $levelLike = $levelNo;
        if($type == 2){
            $sql = <<<SQL
select
*
from t_wsyq_distribution_user_relation t
inner join t_wx_user w on t.userId = w.unionid
left join t_wsyq_user_shopkeeper s on s.user_id = w.userid
where
levelNo like '$levelLike%' and levelNo != '$levelNo' and (LENGTH(levelno )=$levelLen or s.insert_time is null)
SQL;
        }else {
            for ($i = 0; $i < $type + 1; $i++) {
                $levelLike .= '____';
            }
            $sql = <<<SQL
select
*
from t_wsyq_distribution_user_relation t
inner join t_wx_user w on t.userId = w.unionid
inner join t_wsyq_user_shopkeeper wss on w.userid = wss.user_id
where levelNo like '$levelLike' and levelNo != '$levelNo'
SQL;
        }

        return $sql;
    }

    function getChildAction(){

        $pagenum = $this->config->application->pagenum;

        $cur_page = intval($this->getRequest()->getPost('page',1));
        $limit      = ($cur_page > 0 ? $cur_page -1 : 0)*$pagenum;
        $type = intval($this->getRequest()->getPost('type'));

        $levelLike = M('t_wsyq_distribution_user_relation')->get('levelNo',['userId'=>$this->user['unionid']]);

        $keyword = trim($this->getRequest()->getPost('key'));

        if(empty($levelLike)){
            $this->success('没有下线!');
        }

        $sql = $this->_child_sql($levelLike,$type);

        if(!empty($keyword)){
            $sql .= " AND w.nickname like '%$keyword%'";
        }
        $num = M()->query(str_replace('*','count(*)',$sql))->fetchColumn();

        $column = "w.nickname,w.headimgurl,if(w.sex = 0,'未知',if(w.sex = 1,'男','女')) as sex";
        $query = M()->query(str_replace('*',$column,$sql).' limit '.$limit.','.$pagenum);
        $list = $query ? $query->fetchAll(PDO::FETCH_ASSOC) : [];

        $content = '';

        $tpl = '<p style="line-height:30px;height:62px;"><img style="float:left;margin-right: 10px;width: 55px;height: 55px;"  class="img-rounded" src="%s">%s<br />  &nbsp;&nbsp;&nbsp;%s</p>';
        foreach($list as $item){
            $content .= sprintf($tpl,$item['headimgurl'],$item['nickname'],$item['sex']);
        }

        $this->ajaxReturn(['msg'=>'','status'=>1,'content'=>$content,'num'=>$num/$pagenum,'page'=>$cur_page]);
    }

    function saveShopAction(){


    }

    function syncAction(){

        //开始注册流程,首先获取微信用户的详细信息
        $userinfo = $this->wechat->getUserInfo($this->user['openid']);

        if(!empty($userinfo)){

            $model = new WxUserModel();
            $model->save($userinfo);
        }

        $this->redirect('/member/index/index.html');
    }
}
